var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// 引入数据库连接池
const db = require('./db/index');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
const { fetchExternalData } = require('./utils/index');
app.use((req, res, next) => {
  console.log(`${req.method} request for '${req.url}' - ${JSON.stringify(req.body)}`);
  // 或者保存到文件、数据库等
  next();
});
let page = 1;
async function getDataFromExternalAPI() {
  try {
    // api.youpin898.com/api/homepage/new/es/template/GetCsGoPagedList

    let apiData = {
      // "filterMap":{},
      "gameId":730,
      "listSortType":0,
      "listType":2,
      "pageIndex":1,
      "pageSize":100,
      // "propertyFilterTags":[],
      "sortType":0,
      // "stickerAbrade":0,
      // "stickersIsSort":false,
      // "Sessionid":"ZywnOHcgMJMDABFVpbuaQ8Nk"
    };
    const data = await fetchExternalData(`https://api.youpin898.com/api/homepage/new/es/template/GetCsGoPagedList`,apiData);
    console.log('Fetched data:', data);
    if (data && data.Data) {
      await upsertJewelryItem(data.Data[0]);
      for (const item of data.Data) {
        await upsertJewelryItem(item);
      }
      console.log(data.TotalCount);
      console.log(data.Data.length);
      console.log(page*100);
      if (page<100) {
        page++
      }else{
        page = 1
      }
    }
  } catch (error) {
    console.error('Failed to fetch data:', error);
  }
}
async function upsertJewelryItem(item) {
  const { 
    Id, 
    OnSaleCount, 
    Price, 
    SteamPrice, 
    SteamUSDPrice,
    CommodityName,
    CommodityHashName,
    IconUrl,
    IconUrlLarge,
    TypeName,
    Exterior,
    ExteriorColor,
    Rarity,
    RarityColor,
    Quality,
    QualityColor 
  } = item;
  let yyid = Id
  const fields = [
    OnSaleCount,
    Price,
    SteamPrice,
    SteamUSDPrice,
    CommodityName,
    CommodityHashName,
    IconUrl,
    IconUrlLarge,
    TypeName,
    Exterior,
    ExteriorColor,
    Rarity,
    RarityColor,
    Quality,
    QualityColor
  ];
  // 将 undefined 替换为 null
  const values = fields.map(value => value === undefined ? null : value);
  try {
    const [rows] = await db.execute('SELECT * FROM jewelry_list WHERE yyid = ?', [yyid]);
    if (rows.length > 0) {
      // 更新现有记录
      await db.execute(
        'UPDATE jewelry_list SET OnSaleCount = ?, Price = ?, SteamPrice = ?, SteamUSDPrice = ?, CommodityName = ?, CommodityHashName = ?, IconUrl = ?, IconUrlLarge = ?, TypeName = ?, Exterior = ?, ExteriorColor = ?, Rarity = ?, RarityColor = ?, Quality = ?, QualityColor = ? WHERE yyid = ?',
        [...values, yyid]
      );
      console.log(`更新数据 yyid ${yyid}`);
    } else {
      // 插入新记录
      await db.execute(
        'INSERT INTO jewelry_list (yyid,  OnSaleCount, Price, SteamPrice, SteamUSDPrice,CommodityName,CommodityHashName,IconUrl,IconUrlLarge,TypeName,Exterior,ExteriorColor,Rarity,RarityColor,Quality,QualityColor) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
        [yyid, ...values]
      );
      console.log(`插入新数据 yyid ${yyid}`);
    }
  } catch (error) {
    console.error('Error upserting jewelry item:', error);
  }
}
// getDataFromExternalAPI();
setInterval(getDataFromExternalAPI, 1000 * 10);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
